package com.jozen.smart_toilet_system.tcpsocket;

import android.text.TextUtils;
import android.util.Log;

import com.jozen.modelbase.netwoek.Common;
import com.jozen.modelbase.netwoek.eventbus.EventBean;
import com.orhanobut.logger.Logger;

import org.greenrobot.eventbus.EventBus;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 客户端tcp socket 服务
 */
public class ServerSocketUtil {
    private static volatile ServerSocketUtil serverSocketUtil;
    private PrintWriter mPrintWriter;

    /**
     * ServerSocketUtil 单例模式 - 双重校验锁
     */
    public static ServerSocketUtil getInstance() {
        if (serverSocketUtil == null) {
            synchronized (ServerSocketUtil.class) {
                if (serverSocketUtil == null) {
                    serverSocketUtil = new ServerSocketUtil();
                }
            }
        }
        return serverSocketUtil;
    }

    /**
     * 初始化服务
     */
    public void init() {
        try {
            //服务器对象，定义一个端口
            ServerSocket server = new ServerSocket(Common.PORt);
            //客户端对象
            Socket socket = null;
            boolean flag = true;
            while (flag) {
                Log.d("Alex", "等待客户端请求......");
                // 这里是阻塞方法，接收下一个客户端Socket对象
                socket = server.accept();
                //接受客户端传来的字符串
                Log.d("Alex", "新客户端连接......");
                try {
                    mPrintWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(
                            socket.getOutputStream())), true);
                } catch (IOException e) {
                    e.printStackTrace();
                }

                try {
                    //负责读取从客户端发送过来的字符串
//                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream(), "GBK"));
                    boolean clientFlag = true;
                    while (clientFlag) {
                        try {
                            InputStream inputStream = socket.getInputStream();
                            char[] chars = new char[1];
                            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "gbk");
                            StringBuilder sb = new StringBuilder();
                            boolean flag2 = false;
                            while (true) {
                                int read = inputStreamReader.read(chars);
                                if (read != -1) {
                                    if (flag2) {
                                        if (chars[0] != '{') {
                                            continue;
                                        } else {
                                            flag2 = false;
                                        }
                                    }
                                    if (chars[0] == ']') {
                                        sb.append("]}");
                                        flag2 = true;
                                        Logger.d("Alex经过处理的数据=====》" + sb.toString().trim());
                                        EventBus.getDefault().post(new EventBean(Common.TCP_SOCKET_DATA_MSG, sb.toString().replaceAll("/r/n", "").trim()));
                                        sb = new StringBuilder();
                                    } else {
                                        sb.append(chars[0]);
                                    }
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            clientFlag = false;
                            Log.d("Alex", "数据读取异常......");
                            Log.d("Alex", e.toString());
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    Log.d("Alex", "输入流组装异常......");
                    Log.d("Alex", e.toString());
                } finally {
                    socket.close();
                }
            }
            server.close();
            Log.d("Alex", "服务器已经关闭.........");
        } catch (Exception e) {
            e.printStackTrace();
            Log.d("Alex", "客户端连接异常......");
            Log.d("Alex", e.toString());

        }
    }

    /**
     * 向客服端发送消息
     *
     * @param msg 消息
     */
    public void sendMessage(String msg) {
        if (!TextUtils.isEmpty(msg) && mPrintWriter != null) {
            mPrintWriter.println(msg);
        }
    }
}
